package com.study.talk

import android.app.Activity
import android.app.Application
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.study.talk.data.local.AppDatabase
import com.study.talk.data.model.GroupInfo
import com.study.talk.data.model.User
import com.study.talk.data.model.UserInfo
import com.study.talk.netty.message.response.LoginResponse
import com.study.common.EventBusUtil
import com.study.common.event.Constants
import com.study.common.event.OtherMessage
import com.study.talk.data.local.ChatCacheDao
import com.study.talk.data.local.GroupInfoDao
import com.study.talk.data.local.GroupMessageDao
import com.study.talk.data.local.MessageDao
import com.study.talk.data.local.UserInfoDao
import com.study.talk.di.AppModule
import com.study.talk.ui.app.common.FloatViewService
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class App : Application(){

    private val tag = "App"

    private val _user by lazy { MutableLiveData<User>() }
    private val _userInfo by lazy { MutableLiveData<UserInfo>() }
    private val _friendList by lazy { MutableLiveData<List<UserInfo>>() }
    private val _groupList by lazy { MutableLiveData<List<GroupInfo>>() }

    private val db: AppDatabase by lazy { AppDatabase.getInstance(applicationContext) }

    var hide: Boolean = false

    val user: User get() = user()
    val userInfo: UserInfo get() = userInfo()
    val friends: LiveData<List<UserInfo>> get() = _friendList
    val groups: LiveData<List<GroupInfo>> get() = _groupList
    val localUserId: Int get() = userId()
    val username: String get() = username()
    val avatar: String get() = avatar()

    fun updateFriends(friends: List<UserInfo>) {
        _friendList.postValue(friends)
    }

    fun updateGroups(groups: List<GroupInfo>) {
        _groupList.postValue(groups)
    }

    fun updateUserInfo(userInfo: UserInfo) {
        _userInfo.postValue(userInfo)
    }

    private fun user(): User {
        if (_user.value == null) {
            EventBusUtil.sendEvent(OtherMessage(Constants.NEED_LOGIN))
            return User()
        } else {
            return _user.value!!
        }
    }

    private fun userInfo(): UserInfo {
        if (_userInfo.value == null) {
            EventBusUtil.sendEvent(OtherMessage(Constants.NEED_LOGIN))
            return UserInfo()
        } else {
            return _userInfo.value!!
        }
    }

    private fun getFriends(): List<UserInfo> {
        if (_friendList.value == null) {
            EventBusUtil.sendEvent(OtherMessage(Constants.NEED_LOGIN))
            return listOf()
        } else {
            return _friendList.value!!
        }
    }

    private fun getGroups(): List<GroupInfo> {
        if (_groupList.value == null) {
            EventBusUtil.sendEvent(OtherMessage(Constants.NEED_LOGIN))
            return listOf()
        } else {
            return _groupList.value!!
        }
    }

    fun userId(): Int {
        if (_user.value == null) {
            EventBusUtil.sendEvent(OtherMessage(Constants.NEED_LOGIN))
            return -1
        } else {
            return _user.value!!.id
        }
    }

    fun username(): String {
        if (_user.value == null) {
            EventBusUtil.sendEvent(OtherMessage(Constants.NEED_LOGIN))
            return ""
        } else {
            return _user.value!!.username
        }
    }

    fun avatar(): String {
        if (_userInfo.value == null) {
            EventBusUtil.sendEvent(OtherMessage(Constants.NEED_LOGIN))
            return ""
        } else {
            return _userInfo.value!!.avatar
        }
    }

    fun login(response: LoginResponse) {
        //保存账号密码
        getSharedPreferences("account", Context.MODE_PRIVATE).edit().apply {
            putString("username", response.username)
            putString("password", response.user.password)
        }.apply()
        response.apply {
            AppModule.setToken(token)
            _user.postValue(user)
            _userInfo.postValue(userInfo)
            _friendList.postValue(getFriendList())
            _groupList.postValue(getGroupList())
        }
    }

    fun logout() {
        getSharedPreferences("account", MODE_PRIVATE).edit().clear().apply()
        groupMsgDao().clear()
        msgDao().clear()
        cacheDao().clear()
    }

    private fun msgDao(): MessageDao {
        return db.messageDao()
    }

    private fun groupMsgDao(): GroupMessageDao {
        return db.groupMessageDao()
    }

    fun cacheDao(): ChatCacheDao {
        return db.chatCacheDao()
    }

    fun userDao(): UserInfoDao {
        return db.userInfoDao()
    }

    fun groupDao(): GroupInfoDao {
        return db.groupInfoDao()
    }

    override fun onCreate() {
        super.onCreate()
        var activityCount = 0
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                //可以在这里add
            }

            override fun onActivityStarted(activity: Activity) {
                activityCount++
                if (activityCount == 1 && hide) {
                    Log.d(tag, "onActivityStarted: 回到前台")
                    hide = false
                }
            }

            override fun onActivityResumed(activity: Activity) {}

            override fun onActivityPaused(activity: Activity) {}

            override fun onActivityStopped(activity: Activity) {
                activityCount--
                if (activityCount <= 0 && !hide) {
                    hide = true
                    Log.d(tag, "onActivityStopped: 进入后台")
                }
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

            override fun onActivityDestroyed(activity: Activity) {
                //可以在这里remove
            }
        })
    }

    var aiServiceBinder: FloatViewService.FloatViewBinder? = null

    private val serviceConnection = object : ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            aiServiceBinder = service as FloatViewService.FloatViewBinder
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            aiServiceBinder = null
        }

    }

    private fun initAiService(){
        bindService(Intent(this,FloatViewService::class.java),serviceConnection, BIND_AUTO_CREATE)
    }

    private fun unBindAiService(){
        unbindService(serviceConnection)
    }
}
